package mrpanyu.guitool.base.view.swing;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import mrpanyu.guitool.base.model.ToolModel;
import mrpanyu.guitool.base.util.Log;

public class GuiMultiToolFrame extends JFrame {

	private static final long serialVersionUID = 1L;

	private static GuiMultiToolFrame instance;

	public static GuiMultiToolFrame getInstance() {
		return instance;
	}

	private GuiConfig guiConfig;
	private JList<String> listTools;
	private JPanel panelMain;

	public GuiMultiToolFrame(List<ToolModel> toolModels) {
		this(toolModels, null);
	}

	public GuiMultiToolFrame(List<ToolModel> toolModels, GuiConfig guiConf) {
		if (guiConf == null) {
			guiConf = new GuiConfig();
		}
		this.guiConfig = guiConf;
		JSplitPane splitPane = new JSplitPane();
		this.getContentPane().add(splitPane, BorderLayout.CENTER);
		List<String> toolNames = new ArrayList<String>();
		for (ToolModel toolModel : toolModels) {
			toolNames.add(toolModel.getDisplayName());
		}
		listTools = new JList<String>(toolNames.toArray(new String[toolNames.size()]));
		int width = guiConfig.getMultiToolMenuWidth();
		int height = guiConfig.getWindowHeight();
		listTools.setPreferredSize(new Dimension(width, height));
		Font font = new Font("", Font.BOLD, guiConfig.getFontSize());
		listTools.setFont(font);
		listTools.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				if (!e.getValueIsAdjusting()) {
					int index = listTools.getSelectedIndex();
					panelMain.removeAll();
					GuiToolPanelBuilder tpb = new GuiToolPanelBuilder(toolModels.get(index), guiConfig);
					Log.setTool(tpb);
					panelMain.add(tpb.getJPanel(), BorderLayout.CENTER);
					GuiMultiToolFrame.this.pack();
					tpb.onload();
				}
			}
		});
		splitPane.setLeftComponent(listTools);
		panelMain = new JPanel();
		panelMain.setLayout(new BorderLayout());
		width = guiConfig.getWindowWidth();
		height = guiConfig.getWindowHeight();
		panelMain.setPreferredSize(new Dimension(width, height));
		splitPane.setRightComponent(panelMain);
		this.pack();
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setTitle("Tools");
		this.setIconImage(new ImageIcon(this.getClass().getResource("images/tools.png")).getImage());
		this.setLocationByPlatform(false);
		this.setLocationRelativeTo(null);
		this.setVisible(true);
		listTools.setSelectedIndex(0);
		instance = this;
	}

}
